using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using System.IO.Ports;
using System.Text;
using System.Collections;

#if MINI
using SecretLabs.NETMF.Hardware.NetduinoMini;
#else
using SecretLabs.NETMF.Hardware.Netduino;
#endif

namespace codebase
{
    public class RDM630RFID
    {
        SerialPort sr = null;
        public string tagScan = null;

        public bool Initialize(string port)
        {
            sr = new SerialPort(port, 9600, Parity.None, 8, StopBits.One);
            sr.Open();

            Thread.Sleep(1000);

            if (!sr.IsOpen) return false;

            sr.DataReceived += new SerialDataReceivedEventHandler(sr_DataReceived);

            return true;
        }

        private void sr_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (sr.BytesToRead < 14) return;

            byte[] bytes = new byte[14];
            sr.Read(bytes, 0, 14);

            byte[] textbytes = new byte[10];
            for (int i = 0; i < 10; i++)
            {
                
                textbytes[i] = bytes[i + 1];
            }

            byte checksum = bytes[12];
            byte _checksum = 0x00;

            tagScan = "";

            char[] textchars = UTF8Encoding.UTF8.GetChars(textbytes);
            foreach(char c in textchars)
            {
                tagScan += c;
                if (_checksum == 0x00) _checksum = (byte)c; 
                else _checksum ^= (byte)c;
            }

            sr.DiscardInBuffer();

            return;
        }
    }
}
